package action;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import service.NoteService;
import service.UserService;
import com.opensymphony.xwork2.ActionSupport;

import entity.Dir;
import entity.Note;
import entity.User;
import org.springframework.stereotype.Component;

public class UserAction extends BaseAction{
	@Resource(name = "userService")
	private UserService userService;
	private User user;
	private String param;
	private int type;

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public String login() {
		User u = new User();
		String check = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(param);
		//判断用户名还是Email登陆
		 if(matcher.matches()) {
			 user.setEmail(param);	
		 }else {
			 user.setUserName(param);
		 }
		 //登陆
		 u = userService.login(user);	
		try {
			if(u != null) {
				session.put("user", u);
//				System.out.println(session);
				response.getWriter().print("{\"info\":\"信息验证通过！\",\"status\":\"y\"}");
			}else {
				response.getWriter().print("{\"info\":\"登陆失败！请检查您的登陆信息！\",\"status\":\"n\"}");
			}
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
	public String reg() throws Exception{
		user.setCreateTime(new Date());
		if(userService.reg(user)) {
			response.getWriter().println("{\"info\":\"恭喜你！注册成功！\",\"status\":\"y\"}");
		}else {
			response.getWriter().println("{\"info\":\"服务器错误！\",\"status\":\"n\"}");
		}
		return null;
	}
	
	public String check() throws Exception{
		if(type == 1) {
			if(userService.check(param, type)) {
				response.getWriter().println("{\"info\":\"(用户名可以使用！)\",\"status\":\"y\"}");			
			}else {
				response.getWriter().println("{\"info\":\"(用户名已经存在！)\",\"status\":\"n\"}");
			}
		}else {
			if(userService.check(param, type)) {
				response.getWriter().println("{\"info\":\"(E-mail可以使用！)\",\"status\":\"y\"}");				
			}else {
				response.getWriter().println("{\"info\":\"(E-mail已经存在！)\",\"status\":\"n\"}");
			}
		}
		return null;
	}
	
	public String main() {
		// Do Something
		return "main";
	}
	
}
